package ch.zbw.sysventory.server.scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ch.zbw.sysventory.server.model.Computer;
import ch.zbw.sysventory.server.model.ComputerScan;
import ch.zbw.sysventory.server.scanner.adapter.ScanResultAdapter;
import ch.zbw.sysventory.server.scanner.xml.ScanResultXmlReaderFactory;
import ch.zbw.sysventory.server.service.ComputerService;
import ch.zbw.sysventory.transport.model.ScanResult;

@Component
public class ComputerScanner {

	@Autowired
	private ComputerSocketCommunicator computerSocketCommunicator;

	@Autowired
	private ComputerService computerService;

	@Autowired
	private ScanResultAdapter scanResultAdapter;

	public void scanComputer(String ipAddress, int port, ComputerScan computerScan) throws Exception {
		this.sendNewComputerIdIfRequired(ipAddress, port);
		Computer computer = this.computerService.get(this.computerSocketCommunicator.getComputerId(ipAddress, port));
		if (computer != null) {
			String xml = this.computerSocketCommunicator.getLatestScanResultXml(ipAddress, port);
			if (xml != null && !"".equals(xml)) {
				ScanResult scanResult = ScanResultXmlReaderFactory.getScanResultXmlReader().readScanResultXml(xml);
				if (scanResult != null)
					this.scanResultAdapter.importScanResult(scanResult, ipAddress, computer, computerScan);
			}
		}
	}

	private void sendNewComputerIdIfRequired(String ipAddress, int port) throws Exception {
		Long computerId = this.computerSocketCommunicator.getComputerId(ipAddress, port);
		Computer computer = null;
		if (computerId > 0)
			computer = this.computerService.get(computerId);

		if (computer == null) {
			computer = this.computerService.createNewComputer();
			this.computerSocketCommunicator.sendNewComputerId(ipAddress, port, computer.getId());
		}
	}

}
